import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'

import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
  // baseURL: 'http://ihrm-java.itheima.net'
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.success) {
      // Message.success(response.data.message)
    } else {
      Message.error(response.data.message)
    }
    return response.data
  },
  async error => {
    if (error.response.data.code === 10002) {
      // console.log(router.currentRoute)
      await store.dispatch('user/logout')
      location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export default service
